﻿using L.EntityFramework;
using MySql.Data.MySqlClient;
using NB.MGJ.FrameWork;
using NB.MGJ.Model;
using NB.MGJ.Model.AntiFleeingEntity;
using NB.MGJ.Model.CodeManage;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NB.MGJ.Service
{

    public partial class CodeManageService : BaseService
    {
        public BaseRepository _baseRepository = new BaseRepository();
        public ManagerService _ManagerService = new ManagerService();

        private BaseRepository<L.EntityModel.EntityContext> baseRepository2;
        public CodeManageService()
        {
            baseRepository2 = CreateBaseRepository<L.EntityModel.EntityContext>();
        }

        #region 生码手机端
        public PagedList<GenCodeModel> GetGenCodePagedList(ref PagerModel pager, string searchKey)
        {
            pager.FldName = @" * ";
            pager.TblName = @" (SELECT
                                A.ID AS GenCodeId,
                                A.CodeType,
                                A.Gen_Code_Nums,
                                A.Query_Result_Content,
                                A.Query_Tel_Content,
                                A.Query_Message_Content,
                                A.LabelImage,
                                A.ChangeLoginID,
                                A.EnterpriseId,
                                A.ViewDel,
                                A.ChangeDate,
                                B.ID AS BatchId,
                                B.Batch,
                                B.ProductBatchId,
                                C.ID AS CustomerId,
                                C.ProdoctBrand AS ProductBrand,
                                C.EnterpriseUse,
                                D.ID AS ProductId ,
                                D.ProductName,
                                D.TypeId AS ProductTypeId,
                                E.EnterpriseName
                                FROM codemanage_gencode A
                                LEFT JOIN codemanage_gencodebatch B ON A.PatchId = B.ID
                                LEFT JOIN codemanage_card C ON B.ID = C.BatchID 
                                LEFT JOIN product_product D ON B.ProductId = D.Id
                                LEFT JOIN organization_enterprise E ON A.EnterpriseId = E.ID
                                ) F ";

            if (string.IsNullOrEmpty(pager.FldSort) || pager.FldSort == "")
            {
                pager.FldSort = " F.GenCodeId  asc ";

            }

            MySqlParameter[] parameters = _baseRepository.SqParameterRefactor(ref pager);

            IEnumerable<GenCodeModel> resultList = _baseRepository.ExecuteStoredProcedureCollection<GenCodeModel>("Common_PageList", parameters);

            return new PagedList<GenCodeModel>(resultList, pager.Page, pager.PageSize, 1, Convert.ToInt32(parameters[6].Value)); ;

        }

        public void GenCodeUpdate(int genCodeId, string enterpriseUse, string Qrc, string Qmc, string ProductBrand, int? BatchId, int? ProductId, int? CustomerId)
        {
            var _sql = string.Empty;
            _sql += string.Format("UPDATE codemanage_gencode SET Query_Result_Content = '{0}',Query_Message_Content='{1}'  WHERE ID={2};", Qrc, Qmc, genCodeId);
            if (BatchId.HasValue && ProductId.HasValue)
            {
                _sql += string.Format("UPDATE codemanage_gencodebatch SET ProductId={0} WHERE ID ={1};", ProductId.Value, BatchId.Value);
            }
            if (CustomerId.HasValue && (!string.IsNullOrWhiteSpace(enterpriseUse) || !string.IsNullOrWhiteSpace(ProductBrand)))
            {
                var __set = string.Format("{0}{1}",
                     string.IsNullOrWhiteSpace(enterpriseUse) ? string.Empty : string.Format("SET EnterpriseUse='{0}'", enterpriseUse),
                     string.IsNullOrWhiteSpace(ProductBrand) ? string.Empty : string.Format(", ProdoctBrand ='{0}'", ProductBrand)
                 );

                _sql += string.Format("UPDATE codemanage_card  {0}  WHERE ID={1};", __set, CustomerId);
            }
            _baseRepository.ExecuteSql<int>(_sql);
        }


        #region 码申请
        public IEnumerable<SelectItem> GetNbenterparise(int enterpriseId)
        {
            return _baseRepository.ExecuteSqlCollection<Organization_Enterprise>(string.Format("SELECT ID,EnterpriseName FROM organization_enterprise WHERE HeadId ={0} AND ViewDel = 0 AND ViewFlag =1", enterpriseId)).Select(p =>
            {
                return new SelectItem
                {
                    Code = p.ID,
                    Name = p.EnterpriseName
                };
            });
        }

        public IEnumerable<CodeManage_Allot> GetUserCodeApplyList(int enterprsieId)
        {
            string sql = string.Format("SELECT * FROM CodeManage_Allot WHERE T_EnterpriseId = {0}  ORDER BY ApplyDate DESC", enterprsieId);
            return _baseRepository.ExecuteSqlCollection<CodeManage_Allot>(sql);
        }

        public void CodeApplyAdd(CodeManage_Apply model)
        {
            _baseRepository.Insert<CodeManage_Apply>(model);
        }

        public void CodeApplyDelete(int Id, int UserId)
        {
            _baseRepository.ExecuteSql<int>(string.Format("DELETE FROM codemanage_allot WHERE ID = {0} AND ApplyUserId = {1} AND HasVerifie = 0", Id, UserId));
        }
        #endregion

        #region 码分配
        public string GetEID(int id)
        {
            string sql = "SELECT EnterpriseName FROM	organization_enterprise WHERE  ID = " + id + " and ViewDel=0";
            var res = _baseRepository.ExecuteText<string>(sql);
            return res;
        }
        public IEnumerable<SelectItem> GetGenCodeBatchList(int enteprriseId, int allotType)
        {

            string _sql = string.Format("SELECT ID,Batch FROM codemanage_gencodebatch WHERE EnterpriseId = {0} AND ViewFlag =1", enteprriseId);
            if (allotType == 1)
            {
                _sql += " AND ProductId = 0  ";
            }
            return _baseRepository.ExecuteSqlCollection<CodeManage_GenCodeBatch>(_sql).Select(p =>
            {
                return new SelectItem
                {
                    Code = p.Id,
                    Name = p.Batch
                };
            });
        }

        public bool CodeAllotAdd(CodeManage_Allot model, bool notSkip = true, bool isAdd = true)
        {
            string _tableName = null;
            if (notSkip)
            {
                string _sql = string.Format(@"SELECT ID FROM  codemanage_allot WHERE  AllotBatchId={0} and F_EnterpriseId ={1}  AND    AllotCount<>0 ", model.AllotBatchId, model.F_EnterpriseId);

                if (model.AllotType == 0)
                {

                    _sql += string.Format(" AND ((StartCode >= {0} AND StartCode <= {1}) OR (EndCode >= {0} AND EndCode <= {1})OR (StartCode = 0	AND EndCode = 0	))", model.StartCode.Value, model.EndCode.Value);
                }

                _sql += " LIMIT 1 ";

                var _result = _baseRepository.ExecuteSqlCollection<CodeManage_Allot>(_sql).FirstOrDefault();
                if (_result != null)
                {
                    return false;
                }
            }
            try
            {
                bool _Exists = ExistsUsingBatchCode(model.F_EnterpriseId, model.T_EnterpriseId, model.AllotBatch, model.AllotType, model.StartCode, model.EndCode, ref _tableName);
                if (_Exists)
                {
                    if (isAdd)
                    {
                        var result = _baseRepository.Insert<CodeManage_Allot>(model);
                        if (result == 0)
                        {
                            return false;
                        }

                    }
                    else
                    {
                        _baseRepository.Update<CodeManage_Allot>(model);
                    }
                    UpdateAntifakeDigitCodeTable(_tableName, model.ProductId, model.AllotType, model.StartCode, model.EndCode, model.T_EnterpriseId);
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return false;
        }

        /// <summary>
        /// 更新生码库中表数据
        /// </summary>
        private bool UpdateAntifakeDigitCodeTable(string tableName, int productId, int allotType, int? sCode, int? eCode, int? teid)
        {

            if (!string.IsNullOrWhiteSpace(tableName))
            {
                using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mgj_codesql"].ConnectionString))
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;
                        if (allotType == 1)
                        {
                            List<int> _result = new List<int>();
                            cmd.CommandText = string.Format("(SELECT ID FROM {0} limit 1)union(SELECT ID FROM {0} order by ID desc limit 1)", tableName);
                            var _reader = cmd.ExecuteReader();
                            while (_reader.Read())
                            {
                                _result.Add(Convert.ToInt32(_reader["ID"]));
                            }
                            if (_result.Count == 1)
                            {
                                sCode = eCode = _result.First();
                            }
                            else
                            {
                                sCode = _result.First();
                                eCode = _result.Last();
                            }
                            _reader.Close();
                        }

                        if (sCode.HasValue && eCode.HasValue)
                        {
                            cmd.CommandText = string.Empty;
                            var _array = GetTheNumberBetweenTwoNumbers(sCode.Value, eCode.Value, 1000);
                            foreach (var item in _array)
                            {
                                cmd.CommandText += string.Format("UPDATE {0} SET ProductId = {2},EnterpriseId={3} WHERE ID IN({1});", tableName, item, productId, teid);
                            }
                            cmd.ExecuteNonQuery();
                            return true;
                        }
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 找出两个数之间的数 含自己
        /// </summary>
        private List<string> GetTheNumberBetweenTwoNumbers(int s, int e, int arrayCondition = 1000)
        {
            List<string> _result = new List<string>();
            List<int> _temp = new List<int>();
            for (int i = s; i <= e; i++)
            {
                if (((i - s) % arrayCondition == 0) && (i - s) != 0)
                {
                    _result.Add(string.Join(",", _temp));
                    _temp.Clear();
                }
                _temp.Add(i);
            }
            _result.Add(string.Join(",", _temp));
            return _result;
        }

        /// <summary>
        /// 获取对应表中是否含有需要数据
        /// </summary>

        private bool ExistsUsingBatchCode(int enterpriseId, int tenterpriseId, string batchCode, int allottype, int? sCode, int? eCode, ref string _tableName)
        {
            var _connectionstring = ConfigurationManager.ConnectionStrings["mgj_codesql"].ConnectionString;
            var _table_name = "nbcodemain.antifake_digitcode";
            if (!string.IsNullOrWhiteSpace(_connectionstring))
            {
                var _enterprise = _baseRepository.ExecuteSqlCollection<Organization_Enterprise>(string.Format("SELECT `Code` FROM organization_enterprise WHERE ID = {0}", enterpriseId)).FirstOrDefault();
                if (_enterprise != null)
                {

                    _tableName = _table_name += _enterprise.Code + batchCode;

                    using (MySqlConnection conn = new MySqlConnection(_connectionstring))
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            conn.Open();
                            cmd.CommandType = CommandType.Text;
                            string _sql = string.Empty, _and = string.Empty;
                            if (allottype == 0)
                            {

                                _sql += string.Format("SELECT COUNT(ID) FROM {0} WHERE productid=0 AND (ID>={1} AND ID<={2}) and stats<>1 ", _table_name, sCode, eCode);
                                cmd.CommandText = _sql;
                                var r = cmd.ExecuteScalar().ToString();
                                return int.Parse(r) == ((eCode.Value + 1) - sCode.Value);

                            }
                            else
                            {//判断禁用的数量是否等于整批数量，若按号段禁用则整批无法分配
                                string sql = string.Format("SELECT count(id) FROM  {0}", _table_name);
                                var num = _baseRepository.GetSingle(sql);
                                int res = Convert.ToInt32(num);
                                string sqls = string.Format("SELECT count(ID) FROM {0} WHERE productid=0  and stats<>1 ", _table_name);
                                var nums = _baseRepository.GetSingle(sqls);
                                int resu = Convert.ToInt32(nums);
                                if (res == resu)
                                {
                                    return true;
                                }

                            }
                        }
                    }
                }
                return false;
            }
            return false;//连接字符异常
        }

        /// <summary>
        /// 获取整批次单标数量
        /// </summary>
        public int GetWholeBatchCount(string eCode, string batchNo)
        {

            string _tablename = string.Format("antifake_digitcode{0}{1}", eCode, batchNo);
            string _connectionstring = ConfigurationManager.ConnectionStrings["mgj_codesql"].ConnectionString;
            if (string.IsNullOrWhiteSpace(_connectionstring))
            {
                return 0;
            }
            try
            {
                using (MySqlConnection conn = new MySqlConnection(_connectionstring))
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = string.Format(" SHOW TABLES LIKE '{0}'", _tablename);
                        object table = cmd.ExecuteScalar();
                        if (table == null)
                        {
                            return 0;
                        }
                        cmd.CommandText = string.Format("SELECT COUNT(1) FROM {0}", _tablename);
                        object _count = cmd.ExecuteScalar();
                        return Convert.ToInt32(_count);
                    }
                }
            }
            catch
            {
                return 0;
            }
        }


        #endregion

        #endregion

        public PagedList<CodeManage_GenCode> GetRowCode(ref PagerModel pager, DetailSearch Smodel)
        {

            pager.FldName = @"*";
            pager.TblName = @"(select cg.ID,cg.CodeType,cg.PatchId,cg.CodeTypeText,oe.ID EnterpriseId,cg.ViewDel,cg.ChangeDate,
                   cg.Gen_Code_Nums,cg.Image,cg.Query_Result_Content,cg.Query_Tel_Content,cg.Query_Message_Content,
                   cg.Status  ,cgc.Batch,cg.Sequence,cgc.ViewFlag,
                   oe.EnterpriseName,oe.Code from CodeManage_GenCode cg left join Organization_Enterprise oe
                   on cg.EnterpriseId=oe.ID
                   left join CodeManage_GenCodeBatch cgc on cg.PatchId=cgc.ID
                   where cg.ViewDel=0
                ) w ";
            string StrCondition = "   1=1 ";

            if (string.IsNullOrWhiteSpace(pager.StrCondition))
            {
                StrCondition = "   1=1 and ViewDel=0 ";
            }
            else
            {
                StrCondition = pager.StrCondition;
            }

            if (Smodel.EnterpriseName != null)
            {
                StrCondition += "  and (EnterpriseName like '%" + Smodel.EnterpriseName + "%')";
            }
            if (Smodel.Batch != null)
            {
                StrCondition += " and (Batch like '%" + Smodel.Batch + "%')";
            }
            if (Smodel.Code != null)
            {
                StrCondition += " and (Code like '%" + Smodel.Code + "%')";
            }

            //if (Smodel != null)
            //{
            //    StrCondition += " and ViewDel=0  and  (w.EnterpriseName like '%" + Smodel.EnterpriseName + "%') and (w.Batch like '%" + Smodel.Batch + "%')and (w.Code like '%" + Smodel.Code + "%') ";
            //}
            if (Smodel.StartDate != "" && Smodel.StartDate != null)
            {
                StrCondition += " and  (left(ChangeDate,10) >= '" + Smodel.StartDate + "')";
            }
            if (Smodel.EndDate != "" && Smodel.EndDate != null)
            {
                StrCondition += " and  (left(ChangeDate,10) <= '" + Smodel.EndDate + "')";
            }
            pager.StrCondition = StrCondition;
            if (string.IsNullOrEmpty(pager.FldSort) || pager.FldSort == "")
                pager.FldSort = " ChangeDate desc ";

            MySqlParameter[] parameters = _baseRepository.SqParameterRefactor(ref pager);
            IEnumerable<CodeManage_GenCode> resultList = _baseRepository.ExecuteStoredProcedureCollection<CodeManage_GenCode>("Common_PageList", parameters);
            return new PagedList<CodeManage_GenCode>(resultList, pager.Page, pager.PageSize, 1, Convert.ToInt32(parameters[6].Value));
        }
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DelRowCodeService(int id)
        {
            CodeManage_GenCode cg = new CodeManage_GenCode();
            cg.ViewDel = 1;
            cg.ID = id;
            cg.ChangeDate = DateTime.Now;
            return _baseRepository.Update<CodeManage_GenCode>(cg);
        }
        /// <summary>
        /// 下拉框查询
        /// </summary>
        /// <returns></returns>
        public List<Organization_Enterprise> GetEnterpriseboxService(string JuniorEnterprise)
        {
            string sql = " select id,EnterpriseName from organization_enterprise where FIND_IN_SET(ID," + JuniorEnterprise + ")";
            return _baseRepository.ExecuteSqlCollection<Organization_Enterprise>(sql).ToList();
        }
        public List<Product_Product> GetSelnameListboxService(int EnterpriseId)
        {
            string sql = "select * from product_product where ViewDel=0 and  EnterpriseId=" + EnterpriseId;
            IEnumerable<Product_Product> _query = _baseRepository.ExecuteSqlCollection<Product_Product>(sql);
            return _query.ToList();
        }

        public List<Product_Product> GetSeltypeListboxService(int ProductId)
        {
            string sql = "SELECT p.ID,p.typename FROM product_producttypes p LEFT JOIN product_product c on c.TypeId=p.ID WHERE c.ID=" + ProductId;
            IEnumerable<Product_Product> _query = _baseRepository.ExecuteSqlCollection<Product_Product>(sql);
            return _query.ToList();
        }
        public List<Product_Batch> GetSelBatchListboxService(int Pid)
        {
            string sql = "SELECT b.ID,b.BatchName FROM product_batch b LEFT JOIN  product_product p on b.ProductId=p.ID where p.ViewDel=0 AND  b.ProductId=" + Pid;
            IEnumerable<Product_Batch> _query = _baseRepository.ExecuteSqlCollection<Product_Batch>(sql);
            return _query.ToList();
        }

        /// <summary>
        /// 生码添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddGenCode(CodeManage_GenCode model)
        {
            //model.ProductBatchId = null;
            //model.ProductId = null;
            //model.TypeID = null;
            int rulset = _baseRepository.Insert<CodeManage_GenCode>(model);
            return rulset;
        }
        public int GetAllotCount(CodeManage_GenCode model, string batch, int allotid)
        {
            string sql = string.Format("update codemanage_allot SET AllotBatch='{0}',AllotBatchId={1},AllotCount={2},HasVerifie={3} where T_EnterpriseId={4} and F_EnterpriseId=1 and ID={5}", batch, model.PatchId, model.Gen_Code_Nums, 1, model.EnterpriseId, allotid);
            int rulset = _baseRepository.ExecuteSql<int>(sql);
            return rulset;
        }
        public int AddGenCodebatch(CodeManage_GenCodeBatch Batch)
        {

            int rulset = _baseRepository.InsertReturnID<CodeManage_GenCodeBatch>(Batch);
            return rulset;
        }
        public string Ecode(int? enterid)
        {

            string sql = "select `Code` from organization_enterprise where id=" + enterid + " and ViewDel=0";
            var result = _baseRepository.GetSingle(sql);
            string results = result.ToString();
            return results;
        }

        public CodeManage_GenCode GetCodeModelId(int id)
        {
            string sql = "SELECT cg.ID,CodeType,Status,ExpiryDate,cg.ChangeDate,ActiveType,Gen_Code_Nums,Query_Message_Content,Query_Result_Content,Query_Tel_Content,Anti_Fake_Num,Logistics_Num,LabelImage,PatchId,EnterpriseName,Batch,ProductName,ProductId,P.TypeId,cg.EnterpriseId,ProductBatchId,cd.Title,cd.LabelImgUrl,cd.ProductImgUrl,cg.EnterpriseUse FROM CodeManage_GenCode cg LEFT JOIN Organization_Enterprise oe ON cg.EnterpriseId = oe.ID LEFT JOIN CodeManage_GenCodeBatch cgc ON cg.PatchId = cgc.ID LEFT JOIN product_product p ON p.ID = cgc.ProductId LEFT JOIN product_producttypes ps ON ps.ID = p.TypeId LEFT JOIN codemanage_card cd ON cd.BatchID = cgc.ID  where cg.ID=" + id;
            return _baseRepository.ExecuteSqlCollection<CodeManage_GenCode>(sql).FirstOrDefault();
        }

        public CodeManage_GenCode GetCodeModelId()
        {
            string sql = "SELECT CodeType,Gen_Code_Nums,Query_Message_Content,Query_Result_Content,Query_Tel_Content,Anti_Fake_Num,Logistics_Num,LabelImage,PatchId,EnterpriseName,Batch,ProductName,ProductId,P.TypeId,cg.EnterpriseId FROM CodeManage_GenCode cg LEFT JOIN Organization_Enterprise oe ON cg.EnterpriseId = oe.ID LEFT JOIN CodeManage_GenCodeBatch cgc ON cg.PatchId = cgc.ID LEFT JOIN product_product p ON p.ID = cgc.ProductId LEFT JOIN product_producttypes ps ON ps.ID = p.TypeId";
            var result = _baseRepository.ExecuteSqlCollection<CodeManage_GenCode>(sql).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 根据主键编号查询对象
        /// </summary>
        /// <returns></returns>
        public CodeManage_GenCode GetModel(int id)
        {

            string sql = @"select * from CodeManage_GenCode  where PatchId=@ID and status=1";
            MySqlParameter[] parmars ={
                    new MySqlParameter("@ID",id)
               };
            CodeManage_GenCode model = _baseRepository.ExecuteSqlCollection<CodeManage_GenCode>(sql, parmars).FirstOrDefault();
            return model;
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ///
        public int Updproduct(CodeManage_GenCodeBatch model)
        {
            string sql = "UPDATE codemanage_gencodebatch set  ProductId=" + model.ProductId + ",ProductBatchId=" + model.ProductBatchId + " where EnterpriseId=" + model.EnterpriseId + " and batch=" + model.Batch;
            return _baseRepository.Update<CodeManage_GenCodeBatch>(model);
        }
        public int UpdCode(CodeManage_GenCode model)
        {

            string _connectionString = ConfigurationManager.ConnectionStrings["mgj_basemysql"].ConnectionString;
            if (!string.IsNullOrWhiteSpace(_connectionString))
            {
                using (MySqlConnection conn = new MySqlConnection(_connectionString))
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;
                        string _a = new BaseExecute().GetUpdateSQL<CodeManage_GenCode>(model).ToString();
                        if (!_a.Contains("LabelImage"))
                        {
                            _a = _a.Replace("where", ",`LabelImage`=NULL  where ");
                        }
                        if (!_a.Contains("EnterpriseUse"))
                        {
                            _a = _a.Replace("where", ",`EnterpriseUse`=NULL  where ");
                        }
                        cmd.CommandText = _a;
                        return cmd.ExecuteNonQuery();
                    }
                }
            }
            return 0;
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="qsearch"></param>
        /// <returns></returns>
        public IEnumerable<CodeManage_GenCode> GetAllGenCode(string key)
        {
            var resule = "SELECT cg.ID,cg.ViewDel,CodeType,Gen_Code_Nums,Query_Message_Content,Query_Result_Content,Query_Tel_Content,Anti_Fake_Num,Logistics_Num,LabelImage,PatchId,EnterpriseName,Batch,ProductName,oe.`Code`,cgc.Batch,cg.`Status`,cg.ChangeDate,ProductId,cg.EnterpriseId FROM CodeManage_GenCode cg LEFT JOIN Organization_Enterprise oe ON cg.EnterpriseId = oe.ID LEFT JOIN CodeManage_GenCodeBatch cgc ON cg.PatchId = cgc.ID LEFT JOIN product_product p ON p.ID = cgc.ProductId LEFT JOIN product_producttypes ps ON ps.ID = p.TypeId where cg.ViewDel=0 ";
            if (!string.IsNullOrWhiteSpace(key))
            {
                resule += " and cg.ID IN(" + key + ")";
            }
            return _baseRepository.ExecuteSqlCollection<CodeManage_GenCode>(resule);
        }

        /// <summary>
        /// 下拉框关联
        /// Pass 1
        /// </summary>
        public IEnumerable<SelectItem> GetproductlistService(int EnterpriseId)
        {
            string _sql = "select ID AS `Code`,ProductName AS `Name` from product_product where ViewDel=0 and  EnterpriseId=" + EnterpriseId;
            return _baseRepository.ExecuteSqlCollection<SelectItem>(_sql);
        }
        public List<Product_Product> GetTypehlistService(int ProductId)
        {
            string sql = "SELECT p.ID,p.typename FROM product_producttypes p LEFT JOIN product_product c on c.TypeId=p.ID WHERE c.ID=" + ProductId;
            IEnumerable<Product_Product> _query = _baseRepository.ExecuteSqlCollection<Product_Product>(sql);
            return _query.ToList();
        }
        public List<Product_Batch> GetBatchlistService(int ProductId)
        {
            string sql = "SELECT b.ID,b.BatchName FROM product_batch b LEFT JOIN  product_product p on b.ProductId=p.ID where p.ViewDel=0 AND p.ID=" + ProductId;
            IEnumerable<Product_Batch> _query = _baseRepository.ExecuteSqlCollection<Product_Batch>(sql);
            return _query.ToList();
        }
        /// <summary>
        /// 获取生码批次信息
        /// </summary>
        /// <param name="EnterpriseId"></param>
        /// <returns></returns>
        public string GetCbatchservice(int EnterpriseId)
        {
            int result = 1;
            string sql = @"select Batch from CodeManage_GenCodeBatch where EnterpriseId=" + EnterpriseId + " order by ID desc";
            var obj = _baseRepository.GetSingle(sql);
            if (!(Object.Equals(obj, null)))
            {
                result = Convert.ToInt32(obj.ToString()) + 1;
            }
            return result.ToString().PadLeft(2, '0');
        }
        /// <summary>
        /// 启用禁用
        /// </summary>
        /// <param name="flge"></param>
        /// <param name="CheckValue"></param>
        /// <returns></returns>
        public int GetViewFlagService(int flge, string[] CheckValue, int EnterpriseId)
        {
            string sql;
            int sum = 0;
            for (int i = 0; i < CheckValue.Length; i++)
            {
                sql = string.Format("UPDATE codemanage_gencodebatch SET ViewFlag={0} WHERE ID=( SELECT PatchId FROM  codemanage_gencode WHERE ID={1})", flge, CheckValue[i]);
                sum += _baseRepository.ExecuteSql<int>(sql);
            }
            //string getbatch = "";
            //if (flge == 1 && Stats==1)
            //if (flge == 1)
            //{
            //    var tabname = EnterpriseId;
            //    string sqlstr = string.Format("UPDATE nbcodemain.antifake_digitcode{0}  SET Stats =0 WHERE	EnterpriseId = (SELECT	EnterpriseId FROM codemanage_gencodebatch	WHERE	ViewFlag=1 AND EnterpriseId = {1} and Batch={2}	) AND EnterpriseId = {3}", tabname, EnterpriseId, tabname, EnterpriseId);
            //}
            return sum;
        }
        //判断物流码是否判断数据
        public bool ExistUsingBatOrPro(string WLCodes, string tableName)
        {

            string sql = "select ID from " + tableName + " where Wl_Code in(" + WLCodes + ") and (ProductBatchId<>0 or  ProductId<>0)";
            var codeIds = _baseRepository.ExecuteText<AntiFake_Digitcode>(sql);
            if (codeIds != null) return false;
            else return true;

        }
        //手机端码关联批量修改
        public void BatchUpdateProOrBat(string tableName, int id, int type, string[] _array)
        {
            if (!string.IsNullOrWhiteSpace(tableName))
            {
                using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mgj_codesql"].ConnectionString))
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;

                        cmd.CommandText = string.Empty;

                        int i = 0;
                        foreach (var item in _array)
                        {
                            i++;
                            if (type == 1)//更改产品
                                cmd.CommandText += string.Format("UPDATE {0} SET ProductId = {2} WHERE Wl_Code IN({1});", tableName, item, id);
                            if (type == 2)//更改批次
                                cmd.CommandText += string.Format("UPDATE {0} SET ProductBatchId = {2} WHERE Wl_Code IN({1});", tableName, item, id);

                            if (i % 1000 == 0)
                            {
                                cmd.ExecuteNonQuery();
                                i = 0;
                            }
                        }
                        if (i < 1000) cmd.ExecuteNonQuery();

                        conn.Close();
                    }
                }

            }


        }




        //小程序修改查询次数
        public void UpdateDigitcode(AntiFake_Digitcode model, string tableName)
        {
            string sql = @"  update " + tableName + " set QueryCount=@QueryCount,QueryTime=@QueryTime where ID=@ID";

            MySqlParameter[] parameters = { new MySqlParameter("@QueryCount",model.QueryCount),
                                        new MySqlParameter("@QueryTime",model.QueryTime), 
                                        new MySqlParameter("@ID",model.ID),
                                      };
            int i = _baseRepository.ExecuteText<int>(sql, parameters);
        }


        #region 码禁用


        public bool disablewlcode(CodeManage_CodeRelate model, string codes, int stats)
        {

            string tableName = codes.Substring(0, AppConst.SubStrLen);
            string table = "nbcodemain.antifake_digitcode" + tableName;
            string sql = "update {0} set stats={1} where WL_code in ({2})";
            sql = string.Format(sql, table, stats, codes);
            var results = _baseRepository.ExecuteSql<int>(sql);
            if (model.RelateCodeNums != 0)
            {
                if (results > 0)
                {
                    string sqlstr = string.Format("INSERT INTO CodeManage_CodeRelate (`ProductId`,`ProductBatchId`,`EnterpriseId`,`RelateType`,`Action`,`Sequence`,`StartCode`,`EndCode`,`RelateCodenums`,`ChangeLoginID`,`ChangeDate`,WL_CodeDisable)VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", model.ProductId, model.ProductBatchId, model.EnterpriseId, model.RelateType, model.Action, model.Sequence, model.StartCode, model.EndCode, model.RelateCodeNums, model.ChangeLoginID, model.ChangeDate, codes);
                    _baseRepository.ExecuteSql<int>(sqlstr);

                    return true;
                }

                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }

        }
        /// <summary>
        /// 判断单号物流是否已禁用
        /// </summary>
        /// <param name="WlCode"></param>
        /// <returns></returns>
        public List<AntiFake_Digitcode> ListGetTableStats(string WlCode)
        {
            string tableName = "nbcodemain.AntiFake_Digitcode" + WlCode.Substring(0, AppConst.SubStrLen);
            string sql = string.Format("SELECT Stats FROM {0} where Wl_Code='{1}' ", tableName, WlCode);
            return _baseRepository.ExecuteSqlCollection<AntiFake_Digitcode>(sql).ToList();
        }


        /// <summary>
        /// 获取当前用户的已分配列表与申请列表
        /// </summary>
        public async Task<PagedList<L.EntityModel.CodeManage_Allot>> GetCurrentUserAllotCodePagedList(int pageIndex, int pageSize, int enterpriseId, string serialNum, string productName, string toEnterpriseName, int? verifieState = null)
        {
            var Result = await Task.Run(() =>
            {
                var Query = baseRepository2.Search<L.EntityModel.CodeManage_Allot>(p => p.F_EnterpriseId == enterpriseId);
                if (!string.IsNullOrWhiteSpace(serialNum))
                {
                    Query = Query.Where(p => p.SerialNum.Contains(serialNum));
                }
                if (!string.IsNullOrWhiteSpace(productName))
                {
                    Query = Query.Where(p => p.AllotProductName.Contains(productName));
                }
                if (!string.IsNullOrWhiteSpace(toEnterpriseName))
                {
                    Query = Query.Where(p => p.T_EnterpriseName.Contains(toEnterpriseName));
                }
                if (verifieState.HasValue)
                {
                    Query = Query.Where(p => p.HasVerifie == verifieState.Value);
                }
                Query = Query.OrderByDescending(p => p.ApplyDate);

                return new PagedList<L.EntityModel.CodeManage_Allot>(Query, pageIndex, pageSize);
            });
            return Result;
        }


        #region MyRegion

        //public PagedList<CodeManage_Allot> GetCurrentUserAllotCodePagedList (PagerModel pager, int enterpriseId)
        //{
        //    pager.FldName = "*";
        //    pager.TblName = "codemanage_allot";
        //    string _and = string.Empty;
        //    if (!string.IsNullOrWhiteSpace(pager.StrCondition))
        //    {
        //        _and = " AND ";
        //    }
        //    pager.StrCondition += string.Format(" {1} (F_EnterpriseId ={0})", enterpriseId, _and);
        //    pager.FldSort = "ApplyDate desc";
        //    MySqlParameter[] parameters = _baseRepository.SqParameterRefactor(ref pager);
        //    IEnumerable<CodeManage_Allot> resultList = _baseRepository.ExecuteStoredProcedureCollection<CodeManage_Allot>("Common_PageList", parameters);
        //    return new PagedList<CodeManage_Allot>(resultList, pager.Page, pager.PageSize, 1, Convert.ToInt32(parameters[6].Value));
        //} 
        #endregion

        public List<CodeManage_Allot> ExportExcelFromAllotCode(string key)
        {

            string _sql = string.Format("SELECT *  FROM codemanage_allot Where id in (" + key + ")");
            return _baseRepository.ExecuteSqlCollection<CodeManage_Allot>(_sql).ToList();
        }


        public void RefuseAllotCode(int Id, string reason)
        {

            string _sql = string.Format("UPDATE codemanage_allot SET HasVerifie = 2,VerificationNotes='{0}' WHERE ID = {1}", reason, Id);
            baseRepository2.Update(_sql);
            //_baseRepository.ExecuteSql<int>(_sql);
        }
        public int CodeDisableflag(int startcode, int endcode, string enterpariseid, int id, string batchid, int type, string codes, int action)
        {
            var res = 0;
            if (type == 0)
            {

                string sql = string.Format("UPDATE nbcodemain.antifake_digitcode{0}{1} SET Stats = 0 WHERE	(ID>={2} AND ID<={3})", enterpariseid, batchid, startcode, endcode);
                res = _baseRepository.ExecuteSql<int>(sql);
            }
            else if (type == 1)
            {
                string sqlstr = string.Format("UPDATE nbcodemain.antifake_digitcode{0}{1} set Stats=0", enterpariseid, batchid);
                res = _baseRepository.ExecuteSql<int>(sqlstr);
                if (res > 0)
                {
                    string sql = string.Format("UPDATE codemanage_gencodebatch SET ViewFlag =1 WHERE Batch =(SELECT	CodeBatch	FROM	codemanage_coderelate WHERE	Action = {0} and CodeBatch={1} 	AND RelateType ={2} and EnterpriseId={3}  LIMIT 1) AND EnterpriseId={4}", action, batchid, type, enterpariseid, enterpariseid);
                    int count = _baseRepository.ExecuteText<int>(sql);

                }

            }
            else if (type == 2)
            {
                var code = codes.Substring(0, AppConst.SubStrLen);
                string sqls = string.Format("UPDATE nbcodemain.antifake_digitcode{0} SET Stats = 0 where Wl_Code IN ({1})", code, codes);
                res = _baseRepository.ExecuteSql<int>(sqls);
            }
            return res;

        }



        public int Isadmin(int enterpariseid)
        {
            string sql = "select count(ID) from organization_enterprise where ID=" + enterpariseid + " and CODE='0001' ";
            int result = Convert.ToInt32(_baseRepository.GetSingle(sql));
            return result;
        }
        public int IsBornCode(int enterpariseid, int batchid)
        {
            string sql = "select ChangeDate from codemanage_gencode where EnterpriseId=" + enterpariseid + " and  PatchId=" + batchid + " and `Status`=1 ORDER BY ChangeDate DESC  LIMIT 1";
            int result = Convert.ToInt32(_baseRepository.GetSingle(sql));
            return result;
        }
        public int SetAllotPass(int allotId, int eid, string ename, string time)
        {
            string sql = "UPDATE codemanage_allot set HasVerifie=1,AllotType=1,F_EnterpriseId=" + eid + ",F_EnterpriseName='" + ename + "',AllotDate='" + time + "' where ID=" + allotId + " LIMIT 1";
            int result = Convert.ToInt32(_baseRepository.GetSingle(sql));
            return result;
        }




        #region 进行码操作之前的判断（码禁用，码关联，码冻结），更新相应的表（码禁用，码关联，码冻结）
        private bool ExistsUsingBatchCode_CodeRelate(int enterpriseId, string batchCode, int allottype, int sCode, int eCode, ref string _tableName, int action)
        {
            var _connectionstring = ConfigurationManager.ConnectionStrings["mgj_codesql"].ConnectionString;
            var _table_name = "nbcodemain.antifake_digitcode";
            if (!string.IsNullOrWhiteSpace(_connectionstring))
            {
                var _enterprise = _baseRepository.ExecuteSqlCollection<Organization_Enterprise>(string.Format("SELECT `Code` FROM organization_enterprise WHERE ID = {0}", enterpriseId)).FirstOrDefault();
                if (_enterprise != null)
                {

                    _tableName = _table_name += _enterprise.Code + batchCode;
                    if (_tableName != null)
                    {
                        string sqlstr = "SELECT ID FROM " + _table_name;

                    }
                    using (MySqlConnection conn = new MySqlConnection(_connectionstring))
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            conn.Open();
                            cmd.CommandType = CommandType.Text;
                            //整批  获取这一批次的所有
                            if (allottype == 1)
                            {
                                List<int> _result = new List<int>();
                                cmd.CommandText = string.Format("(SELECT ID FROM {0} limit 1)union(SELECT ID FROM {0} order by ID desc limit 1)", _tableName);
                                var _reader = cmd.ExecuteReader();
                                while (_reader.Read())
                                {
                                    _result.Add(Convert.ToInt32(_reader["ID"]));
                                }
                                if (_result.Count == 1)
                                {
                                    sCode = eCode = _result.First();
                                }
                                else
                                {
                                    sCode = _result.First();
                                    eCode = _result.Last();
                                }
                                _reader.Close();
                            }
                            string _sql = string.Empty, _and = string.Empty;
                            if (allottype == 0)
                            {
                                if (action == 0)
                                {
                                    _sql += string.Format("SELECT COUNT(ID) FROM {0} WHERE ProductId = 0  AND (ID>={1} AND ID<={2})", _table_name, sCode, eCode);
                                }
                                if (action == 1)
                                {
                                    _sql += string.Format("SELECT COUNT(ID) FROM {0} WHERE  (ID>={1} AND ID<={2}) and Stats<>1", _table_name, sCode, eCode);
                                }

                                cmd.CommandText = _sql;

                                var r = cmd.ExecuteScalar().ToString();

                                return int.Parse(r) == ((eCode + 1) - sCode);
                                //return r.Equals(((eCode.Value + 1) - sCode.Value));
                            }
                            else if (allottype == 2)
                            {
                                if (action == 1)
                                {
                                    _sql += string.Format("SELECT COUNT(ID) FROM {0} WHERE ProductId = 0  AND (ID>={1} AND ID<={2})", _table_name, sCode, eCode);
                                }
                            }
                            else
                            {
                                if (action == 0)
                                {
                                    _sql += string.Format("SELECT ID FROM {0} WHERE ProductId = 0  LIMIT 1", _table_name);
                                }
                                if (action == 1)
                                {
                                    _sql += string.Format("SELECT ID FROM {0} WHERE Stats <> 1  LIMIT 1", _table_name);
                                }

                                cmd.CommandText = _sql;

                                int count = _baseRepository.ExecuteText<int>(cmd.CommandText);
                                if (count == 0)
                                {
                                    return false;
                                }
                                return cmd.ExecuteScalar() != null;
                            }
                        }
                    }
                }
                return false;
            }
            return false;//连接字符异常
        }


        private bool UpdateAntifakeDigitCodeTable_CodeRelate(string tableName, int productId, int productBatchId, int ReleteType, int? sCode, int? eCode, int action)
        {
            if (!string.IsNullOrWhiteSpace(tableName))
            {
                using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mgj_codesql"].ConnectionString))
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;

                        //整批  获取这一批次的所有
                        if (ReleteType == 1)
                        {
                            List<int> _result = new List<int>();
                            cmd.CommandText = string.Format("(SELECT ID FROM {0} limit 1)union(SELECT ID FROM {0} order by ID desc limit 1)", tableName);
                            var _reader = cmd.ExecuteReader();
                            while (_reader.Read())
                            {
                                _result.Add(Convert.ToInt32(_reader["ID"]));
                            }
                            if (_result.Count == 1)
                            {
                                sCode = eCode = _result.First();
                            }
                            else
                            {
                                sCode = _result.First();
                                eCode = _result.Last();
                            }
                            _reader.Close();
                        }

                        if (sCode.HasValue && eCode.HasValue)
                        {
                            cmd.CommandText = string.Empty;
                            var _array = GetTheNumberBetweenTwoNumbers(sCode.Value, eCode.Value, 1000);
                            foreach (var item in _array)
                            {
                                if (action == 0)
                                {
                                    cmd.CommandText += string.Format("UPDATE {0} SET ProductId = {2} ,ProductBatchId = {3} WHERE ID IN({1});", tableName, item, productId, productBatchId);
                                }
                                if (action == 1)
                                {
                                    cmd.CommandText += string.Format("UPDATE {0} SET Stats=1 WHERE  (ID>={1} AND ID<={2})", tableName, sCode, eCode);
                                }

                            }
                            cmd.ExecuteNonQuery();
                            return true;
                        }
                        return false;
                    }
                }
            }
            return true;
        }


        public List<string> GetCodeListIdStr(string tableName, int ReleteType, int? sCode, int? eCode)
        {
            var _array = new List<string>();

            if (!string.IsNullOrWhiteSpace(tableName))
            {
                using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mgj_codesql"].ConnectionString))
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;

                        //整批  获取这一批次的所有
                        if (ReleteType == 1)
                        {
                            List<int> _result = new List<int>();
                            cmd.CommandText = string.Format("(SELECT ID FROM {0} limit 1)union(SELECT ID FROM {0} order by ID desc limit 1)", tableName);
                            var _reader = cmd.ExecuteReader();
                            while (_reader.Read())
                            {
                                _result.Add(Convert.ToInt32(_reader["ID"]));
                            }
                            if (_result.Count == 1)
                            {
                                sCode = eCode = _result.First();
                            }
                            else
                            {
                                sCode = _result.First();
                                eCode = _result.Last();
                            }
                            _reader.Close();
                        }

                        if (sCode.HasValue && eCode.HasValue)
                        {
                            cmd.CommandText = string.Empty;
                            _array = GetTheNumberBetweenTwoNumbers(sCode.Value, eCode.Value, 1000);
                        }

                    }
                }
            }
            return _array;
        }







        #endregion

        #region 码禁用
        public bool CodeDisableAdd(CodeManage_CodeRelate model, int eid)
        {
            string tableName = null;
            var isviewflag = "SELECT count(*) from codemanage_gencodebatch where EnterpriseId=" + eid + " and ViewFlag=1 and Batch=" + model.CodeBatch;

            var count = Convert.ToInt32(_baseRepository.GetSingle(isviewflag));
            try
            {
                if (count > 0)
                {
                    bool _Exist = ExistsUsingBatchCode_CodeRelate(model.EnterpriseId, model.CodeBatch, model.RelateType, model.StartCode, model.EndCode, ref tableName, model.Action);
                    if (_Exist)
                    {


                        UpdateAntifakeDigitCodeTable_CodeRelate(tableName, model.ProductId, model.ProductBatchId, model.RelateType, model.StartCode, model.EndCode, model.Action);
                        int result = GetCount(model);
                        if (result == 0)
                        {
                            _baseRepository.Insert<CodeManage_CodeRelate>(model);
                        }
                        else
                        {
                            _baseRepository.Update<CodeManage_CodeRelate>(model);
                        }
                        if (model.Action == 1 && model.RelateType == 1)
                        {
                            UpdateCodeBatchFlag(model.EnterpriseId, model.Action, model.RelateType, model.CodeBatch);
                        }
                        return true;
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }

            return false;
        }
        public int GetCount(CodeManage_CodeRelate model)
        {
            string sql = string.Format(" SELECT count(*) FROM	nbsecuritymain.codemanage_coderelate WHERE	EnterpriseId = {0} AND CodeBatch = '{1}' AND Action = 1 AND StartCode ={2} and EndCode={3}", model.EnterpriseId, model.CodeBatch, model.StartCode, model.EndCode);
            return Convert.ToInt32(_baseRepository.GetSingle(sql));
        }
        private bool UpdateCodeBatchFlag(int EnterpriseId, int Action, int RelateType, string batch)
        {

            string sql = string.Format("UPDATE codemanage_gencodebatch SET ViewFlag =0 WHERE Batch =(SELECT	CodeBatch	FROM	codemanage_coderelate WHERE	Action = {0} and CodeBatch={1} 	AND RelateType ={2} and EnterpriseId={3}  LIMIT 1) AND EnterpriseId={4}", Action, batch, RelateType, EnterpriseId, EnterpriseId);

            int count = _baseRepository.ExecuteText<int>(sql);

            return count > 0;

            //if (count > 0)
            //{
            //    return true;
            //}

            //return true;

        }

        #endregion

        #region 码关联

        //进行码关联之前的判断
        public bool IsCanInsertLogAndBinding(CodeManage_CodeRelate model)
        {

            string _tableName = null,

            _sql = string.Format(@"SELECT ID FROM  codemanage_coderelate WHERE  ProductId = {0} AND ProductBatchId = {1}  AND EnterpriseId = {2}  ", model.ProductId, model.ProductBatchId, model.EnterpriseId);

            if (model.RelateType == 0)
            {
                _sql += string.Format(" AND (StartCode <= {0} AND EndCode >= {0}) AND (StartCode <= {1} AND EndCode >= {1})", model.StartCode, model.EndCode);
            }

            _sql += " LIMIT 1 ";

            var _result = _baseRepository.ExecuteSqlCollection<CodeManage_CodeRelate>(_sql).FirstOrDefault();

            // 1. 查询 码关联记录里面是否有相关的关联记录，如果没有，下一步
            if (_result != null)
            {
                return false;
            }
            //2.查询是否存在序号中标注的码

            int CodeTableEid = 0;
            var EModel = _ManagerService.GetEnterpriseModel_Eid(model.EnterpriseId);
            if (EModel.HeadId != 0 && EModel.HeadId != 1)
            {

                CodeTableEid = Convert.ToInt32(EModel.HeadId);
            }


            return ExistsUsingBatchCode_CodeRelate(CodeTableEid, model.CodeBatch, model.RelateType, model.StartCode, model.EndCode, ref _tableName, model.Action);

            //bool _Exists = ExistsUsingBatchCode_CodeRelate(CodeTableEid, model.CodeBatch, model.RelateType, model.StartCode, model.EndCode, ref _tableName, model.Action);
            //return _Exists;
        }


        //插入码操作记录
        public int CodeRelateInsert(CodeManage_CodeRelate model)
        {
            return _baseRepository.InsertReturnID<CodeManage_CodeRelate>(model);
            //return result;
        }


        //码关联
        public bool CodeRelate(CodeManage_CodeRelate model)
        {
            //插入码操作记录
            CodeRelateInsert(model);

            //3.在相应的表中， 绑定产品ID，批次ID
            string _tableName = "";
            var _table_name = "nbcodemain.antifake_digitcode";

            int CodeTableEid = 0;
            var EModel = _ManagerService.GetEnterpriseModel_Eid(model.EnterpriseId);
            if (EModel.HeadId.HasValue && EModel.HeadId != 0 && EModel.HeadId != 1)
            {
                //CodeTableEid = Convert.ToInt32(EModel.HeadId);
                CodeTableEid = EModel.HeadId.Value;
            }
            else
            {
                CodeTableEid = EModel.ID;
            }

            var _enterprise = _baseRepository.ExecuteSqlCollection<Organization_Enterprise>(string.Format("SELECT `Code` FROM organization_enterprise WHERE ID = {0}", CodeTableEid)).FirstOrDefault();
            _tableName = _table_name += _enterprise.Code + model.CodeBatch;


            return UpdateAntifakeDigitCodeTable_CodeRelate(_tableName, model.ProductId, model.ProductBatchId, model.RelateType, model.StartCode, model.EndCode, model.Action);
            //return true;
        }

        #endregion





































































































        #region 码冻结


        public string GetTableName(string Ecode, string codeBatch)
        {
            string _tableName = "";
            var _table_name = "nbcodemain.antifake_digitcode";
            _tableName = _table_name += Ecode + codeBatch;

            return _tableName;

        }


        public bool CodeRecall(CodeReCallModel _model)
        {
            var model = _model.Model;

            //插入召回记录
            int result = CodeRelateInsert(model);


            //插入召回记录相关经销商 
            var insertLogAndDistributorResult = antifleeing_distributorrecalllogAdd(_model.DistributorList, result);

            var _enterprise = _baseRepository.ExecuteSqlCollection<Organization_Enterprise>(string.Format("SELECT `Code` FROM organization_enterprise WHERE ID = {0}", model.EnterpriseId)).FirstOrDefault();
            string _tableName = GetTableName(_enterprise.Code, model.CodeBatch);

            //将相关的码改成召回状态
            var updateresult = UpdateAntifakeDigitCodeTable_CodeRecall(_tableName, model.RelateType, model.WL_CodeDisable);
            return true;
        }

        private bool UpdateAntifakeDigitCodeTable_CodeRecall(string tableName, int ReleteType, string WL_CodeDisable = "0642004058618225,0642004049627442,0642004098779016")
        {
            string sqlStr = "";
            //单码
            if (ReleteType == 0)
            {

                sqlStr += string.Format("UPDATE {0} SET Stats=2 WHERE 1=1 and Wl_Code in ({1})", tableName, WL_CodeDisable);
            }
            //整批
            if (ReleteType == 1)
            {
                sqlStr += string.Format("UPDATE {0} SET Stats=2 WHERE 1=1", tableName);

            }

            var result = _baseRepository.ExecuteSql<int>(sqlStr);
            if (result >= 0)
            {
                return true;
            }
            else
            {
                return false;

            }
        }

        public int antifleeing_distributorrecalllogAdd(int[] list, int RecallId)
        {

            if (list == null || list.Length <= 0)
            {
                return 0;
            }
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < list.Length; i++)
            {
                int DistributorID = list[i];
                sb.Append("insert into antifleeing_distributorrecalllog (LogId,DistributorId,Status)values(" + RecallId + "," + DistributorID + "," + 0 + ");");
            }
            var sql = sb.ToString();

            var result = _baseRepository.ExecuteSql<int>(sql);

            return result;
        }


        public List<CodeManage_Allot> Getapplylist(int eid)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT *FROM codemanage_allot WHERE F_EnterpriseId=" + eid + " AND HasVerifie=0");
            var sql = sb.ToString();

            var result = _baseRepository.ExecuteSqlCollection<CodeManage_Allot>(sql).ToList();

            return result;
        }

        public List<Antifleeing_DistributorRecallLog> GetRecallListByDistributorId(int DistributorId)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("select * from antifleeing_distributorrecalllog where DistributorId=" + DistributorId);
            var sql = sb.ToString();

            var result = _baseRepository.ExecuteSqlCollection<Antifleeing_DistributorRecallLog>(sql).ToList();

            return result;
        }


        public int UpdateDistributorRecallLogStatus(int Id)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("update antifleeing_distributorrecalllog set Status=1 where Id=" + Id);

            var sql = sb.ToString();

            var result = _baseRepository.ExecuteSql<int>(sql);

            return result;

        }

        #endregion
























    }
}
        #endregion